package com.lagou.client;

import com.lagou.handler.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.time.temporal.ValueRange;
import java.util.concurrent.*;

public class RPCClient {
    private String ip;
    private Integer port;
    private RpcClientHandler rpcClientHandler = new RpcClientHandler();
    private ExecutorService executorService = Executors.newCachedThreadPool();
    private Channel channel;
    private EventLoopGroup eventLoopGroup;

    public RPCClient(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
        init();
    }


    public void init() {

        try {
            eventLoopGroup = new NioEventLoopGroup();
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //String类型编解码器
                            //String类型编解码器
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            //添加客户端处理类
                            pipeline.addLast(rpcClientHandler);
                        }
                    });
            ChannelFuture future = bootstrap.connect(ip, port).sync();
            channel = future.channel();

        } catch (InterruptedException e) {
            e.printStackTrace();
            if (channel != null) {
                channel.close();
            }
            if (eventLoopGroup != null){
                eventLoopGroup.shutdownGracefully();
            }
        }
    }

    /**
     * 提供消息发送的方法
     */
    public Object send(String msg) throws ExecutionException, InterruptedException {
        rpcClientHandler.requestMsg(msg);
        Future submit = executorService.submit(rpcClientHandler);
        return submit.get();
    }

    public void close() {
        if (channel != null) {
            channel.close();
        }
        if (eventLoopGroup != null){
            eventLoopGroup.shutdownGracefully();
        }
    }
}
